package org.recursed.simpleweather;

import java.util.TreeMap;

import android.content.Context;
import android.location.Address;
import android.os.Handler;
import android.text.Editable;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;

public class AddLocation implements OnClickListener, OnKeyListener, OnItemSelectedListener{

	public static final int GEOCODE_STATUS_NETWORK_ERROR = 1;
	public static final int GEOCODE_STATUS_LOOKUP_FAIL = 2;
	public static final int GEOCODE_STATUS_SUCCESS = 3;
	
	private SimpleWeather owner;
	
	private TextView log;
	private EditText enterLocation;
	private Button lookupLocation;
		
	private boolean geocoding;
	protected Handler handler = new Handler();
	
	protected Address geocoded;
	protected int geocodeStatus;
	
	private Context context;
	
	private final class GeocodeResultsHandler implements Runnable {
		public void run() {
			geocodeFinished();
		}
	}
	protected final GeocodeResultsHandler grh = new GeocodeResultsHandler();

	public AddLocation(SimpleWeather owner) {
		this.owner = owner;
		context = owner.getApplicationContext();
        log = (TextView) owner.findViewById(R.id.log);
        enterLocation = (EditText) owner.findViewById(R.id.enterLocation);
        enterLocation.setOnKeyListener(this);
        lookupLocation = (Button) owner.findViewById(R.id.fireLocationLookup);
        lookupLocation.setOnClickListener(this);
		lookupLocation.setEnabled(false);
		geocoding = false;
		Spinner spinner = (Spinner) owner.findViewById(R.id.locationSpinner);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(owner, 
				android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
		spinner.setAdapter(adapter);
		LocationManager locationManager = new LocationManager(owner);
		TreeMap<String, String[]> locations = locationManager.getLocations();
		for (String id : locations.keySet()) {
			String[] vals = locations.get(id);
			adapter.add(vals[0]);
		}
		spinner.setOnItemSelectedListener(this);
        log(owner.getString(R.string.addLocationExample));
	}
	
	private synchronized void geocode(final String place) {
		if (geocoding) {
			return;
		}
		lookupLocation.setEnabled(false);
		log(owner.getString(R.string.searchingForLocation));
		GeocodePlace gp = new GeocodePlace(place, this, context);
		(new Thread(gp)).start();
	}
	
	public void geocodeFinished() {
		lookupLocation.setEnabled(true);
		if (geocodeStatus == GEOCODE_STATUS_SUCCESS) {
			StringBuilder sb = new StringBuilder(owner.getString(R.string.foundLocation));
			sb.append(geocoded.getLocality()).append(" (").append(geocoded.getAdminArea()).append(")");
			log(sb.toString());
			owner.getLocationManager().storeLocation(geocoded);
		} else if (geocodeStatus == GEOCODE_STATUS_NETWORK_ERROR ){
			log(owner.getString(R.string.geocodeNetworkError));
		} else {
			// geocode status will be lookup fail
			log(owner.getString(R.string.geocodeLookupFailure));
		}
		geocoded = null;
		geocodeStatus = 0;
	}

	
	
	public void onClick(View v) {
		if (v == lookupLocation) {
			Editable editable = this.enterLocation.getText();
			String s = editable.toString();
			geocode(s);
		}
	}

	public boolean onKey(View v, int keyCode, KeyEvent event) {
		if (v == enterLocation) {
			Editable editable = this.enterLocation.getText();
			String s = editable.toString();
			if (s.length() == 0) {
				lookupLocation.setEnabled(false);
			} else {
				lookupLocation.setEnabled(true);
			}
			return false;
		}
		if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
			onClick(lookupLocation);
			return true;
		}
		return false;
	}

	public void log(String text) {
    	log.setText(text);
    }

	public void onItemSelected(AdapterView<?> adapter, View arg1, int position,
			long id) {
		String name = (String) adapter.getItemAtPosition(position);
		System.out.println(name);
	}

	public void onNothingSelected(AdapterView<?> arg0) {
		// don't do anything...
	}
	
	
}
